﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace TSharp.Core.TestUtil
{
    public class Performance
    {
        public static TResult MeasurePerformance<TArg, TResult>(Func<TArg, TResult> func, TArg arg, int loop)
        {
            GC.Collect();
            int gc0 = GC.CollectionCount(0);
            int gc1 = GC.CollectionCount(1);
            int gc2 = GC.CollectionCount(2);
            TResult result = default(TResult);
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                result = func(arg);
            }
            Console.WriteLine(sw.ElapsedMilliseconds.ToString() + "ms");
            Console.WriteLine("GC 0:" + (GC.CollectionCount(0) - gc0).ToString());
            Console.WriteLine("GC 1:" + (GC.CollectionCount(1) - gc1).ToString());
            Console.WriteLine("GC 2:" + (GC.CollectionCount(2) - gc2).ToString());
            return result;
        }
        public static void MeasurePerformance<TArg>(TArg arg,
            int loop,
            Action<TArg> funX,
            Action<TArg> funY)
        {
            GC.Collect();
            int xgc0 = GC.CollectionCount(0);
            int xgc1 = GC.CollectionCount(1);
            int xgc2 = GC.CollectionCount(2);

            Stopwatch xsw = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                funX(arg);
            }
            Console.WriteLine("X :" + xsw.ElapsedMilliseconds.ToString() + "ms");
            Console.WriteLine("X GC 0:" + (GC.CollectionCount(0) - xgc0).ToString());
            Console.WriteLine("X GC 1:" + (GC.CollectionCount(1) - xgc1).ToString());
            Console.WriteLine("X GC 2:" + (GC.CollectionCount(2) - xgc2).ToString());
            Console.WriteLine();
            GC.Collect();
            int ygc0 = GC.CollectionCount(0);
            int ygc1 = GC.CollectionCount(1);
            int ygc2 = GC.CollectionCount(2);

            Stopwatch ysw = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                funY(arg);
            }
            Console.WriteLine("Y :" + ysw.ElapsedMilliseconds.ToString() + "ms");
            Console.WriteLine("Y GC 0:" + (GC.CollectionCount(0) - ygc0).ToString());
            Console.WriteLine("Y GC 1:" + (GC.CollectionCount(1) - ygc1).ToString());
            Console.WriteLine("Y GC 2:" + (GC.CollectionCount(2) - ygc2).ToString());

        }
    }
}
